package rapier.sso.server.handler.impl;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import rapier.sso.common.utils.SpringContextUtils;
import rapier.sso.core.entity.TDbSysUserEntity;
import rapier.sso.core.service.ITDbSysUserService;
import rapier.sso.server.handler.IAuthHandler;
import rapier.sso.server.model.Credential;
import rapier.sso.server.utils.PasswordUtil;

@Component
public class PwdAuthHandler implements IAuthHandler {

	@Autowired
	private ITDbSysUserService userBaseService;

	@Override
	public boolean support(Credential credential) {
		HttpServletRequest req = SpringContextUtils.getHttpServletRequest();
		return req.getParameterMap().containsKey("account") && req.getParameterMap().containsKey("password");
	}

	@Override
	public boolean auth(Credential credential) {
		HttpServletRequest req = SpringContextUtils.getHttpServletRequest();
		String account = req.getParameter("account");
		String password = req.getParameter("password");
		TDbSysUserEntity userEntity = null;
		if (credential.getUserEntity() == null) {// 已经存在
			QueryWrapper<TDbSysUserEntity> query = new QueryWrapper<TDbSysUserEntity>();
			query.eq("user_account", account);
			query.last("limit 1");
			userEntity = userBaseService.getOne(query, false);
			credential.setUserEntity(userEntity);
		} else {
			userEntity = credential.getUserEntity();
		}
		if (userEntity == null) {
			credential.setError("用户不存在!");
			return false;
		}
		String userpassword = PasswordUtil.encrypt(account, password, userEntity.getSalt());
		if (userEntity.getPasswd() == null || !userEntity.getPasswd().equals(userpassword)) {
			credential.setError("帐号或密码错误");
			return false;
		}
		return true;
	}

	@Override
	public void release(Credential credential) {
		// 什么都不用做
	}

}
